"""
核心功能函数模块
- 仅实现与 config.yaml 参数解耦的核心逻辑
"""

import os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tabulate import tabulate

def ensure_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

def save_figure(fig, filename, fig_dir="figures"):
    ensure_dir(fig_dir)
    path = os.path.join(fig_dir, filename)
    fig.savefig(path, dpi=300, bbox_inches='tight')
    print(f"图片已保存：{path}")
    return path

def show_all_images(image_paths):
    for path in image_paths:
        try:
            img = Image.open(path)
            img.show()
        except Exception as e:
            print(f"图片 {path} 打开失败：{e}")

def plot_radar_chart(mean_table, score_fields, years, save_path=None, figsize=(7,7), font_family="Heiti TC"):
    """
    mean_table: DataFrame, index为年份，列为score_fields
    years: 要展示的年份列表
    figsize: 雷达图尺寸
    font_family: 中文字体
    """
    labels = score_fields
    num_vars = len(labels)
    angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
    angles += angles[:1]  # 闭合

    fig, ax = plt.subplots(figsize=figsize, subplot_kw=dict(polar=True))
    colors = ['#1f77b4', '#ff7f0e', '#2ca02c']

    for idx, year in enumerate(years):
        values = mean_table.loc[year, labels].tolist()
        values += values[:1]
        ax.plot(angles, values, label=str(year), color=colors[idx % len(colors)], linewidth=2)
        ax.fill(angles, values, color=colors[idx % len(colors)], alpha=0.15)

    ax.set_theta_offset(np.pi / 2)
    ax.set_theta_direction(-1)
    ax.set_thetagrids(np.degrees(angles[:-1]), labels)
    ax.set_title("三年四项计分均值雷达图", fontsize=16, fontfamily=font_family)
    ax.legend(loc='upper right', bbox_to_anchor=(1.2, 1.05))
    plt.tight_layout()
    if save_path:
        fig.savefig(save_path, dpi=300, bbox_inches='tight')
        print(f"雷达图已保存：{save_path}")
    plt.close(fig)

def get_mean_table(df, score_fields, year_field):
    """分组均值统计"""
    return df.groupby(year_field)[score_fields].mean()

def print_mean_table(mean_table):
    print("\n【各年份四项计分均值】")
    print(tabulate(mean_table, headers='keys', tablefmt='github', floatfmt=".2f"))

def get_box_stats(df, score_fields, year_field):
    """分布对比（箱线统计）"""
    stats = {}
    for field in score_fields:
        desc = df.groupby(year_field)[field].describe()[["count", "mean", "std", "min", "25%", "50%", "75%", "max"]]
        stats[field] = desc
    return stats

def print_box_stats(stats):
    print("\n【各年份四项计分分布（箱线统计）】")
    for field, desc in stats.items():
        print(f"\n字段：{field}")
        print(tabulate(desc, headers='keys', tablefmt='github', floatfmt=".2f"))

def anova_by_year(df, score_fields, year_field):
    """方差分析（ANOVA）"""
    from scipy.stats import f_oneway
    results = []
    for field in score_fields:
        groups = [g.dropna().values for name, g in df.groupby(year_field)[field]]
        if all(len(g) > 1 for g in groups):
            fval, pval = f_oneway(*groups)
            results.append([field, f"{fval:.2f}", f"{pval:.4f}"])
        else:
            results.append([field, "数据不足", "数据不足"])
    return results

def print_anova_results(results):
    print("\n【方差分析（ANOVA）结果】")
    print(tabulate(results, headers=["字段", "F值", "p值"], tablefmt='github'))
